package com.dinree.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import com.base.library.TopBarBaseActivity;
import com.base.library.utils.JsonUtils;
import com.base.library.widget.CompetitionWebChromeClient;
import com.bigkoo.pickerview.OptionsPickerView;
import com.dinree.R;
import com.dinree.bean.JsonBean;
import com.dinree.bean.UserBean;
import com.dinree.databinding.ActivityAddressWebBinding;
import com.google.gson.Gson;
import com.tencent.smtt.export.external.interfaces.GeolocationPermissionsCallback;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.tencent.smtt.sdk.WebView;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class AddressWebActivity extends TopBarBaseActivity {
    private ActivityAddressWebBinding activityAddressWebBinding;
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private boolean isLoaded = false;
    private UserBean userBean;

    @Override
    public int getContentView() {
        return R.layout.activity_address_web;
    }

    @Override
    public void initContentView(Bundle savedInstanceState) {
        activityAddressWebBinding = getContentViewBinding();
        userBean = realm.findFirst(UserBean.class);
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        setTopLeftButton(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (activityAddressWebBinding.webView.canGoBack()) {
                    activityAddressWebBinding.webView.goBack();
                } else {
                    finish();
                }
            }
        });
        setTopRightButton("管理", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activityAddressWebBinding.webView.loadUrl("javascript:edit(true)");
            }
        });
        String url = getIntent().getStringExtra("url");
        activityAddressWebBinding.webView.addJavascriptInterface(new JSHook(), "dinree");
        if (userBean != null) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("user_id", userBean.user_id);
            map.put("user_token", userBean.user_token);
            map.put("referer", "https://web.dinree.cn/epsea/front");
            activityAddressWebBinding.webView.loadUrl(url, map);
        } else {
            activityAddressWebBinding.webView.loadUrl(url);
        }
        activityAddressWebBinding.webView.setWebChromeClient(new CompetitionWebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO Auto-generated method stub
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                setTitle(title);
            }

            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissionsCallback callback) {
                callback.invoke(origin, true, false);
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }

            @Override
            public void onShowCustomView(View view, IX5WebChromeClient.CustomViewCallback customViewCallback) {
                super.onShowCustomView(view, customViewCallback);
            }
        });
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    isLoaded = true;
                    break;
                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    private void showPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                activityAddressWebBinding.webView.loadUrl("javascript:setAddress('" + options1Items.get(options1).getPickerViewText() + "','" + options2Items.get(options1).get(options2) + "','" + options3Items.get(options1).get(options2).get(options3) + "')");
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setSubmitColor(getResources().getColor(R.color.mainColor))
                .setCancelColor(Color.GRAY)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new JsonUtils().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    public class JSHook {
        @JavascriptInterface
        public void chooseAddress() {
            if (isLoaded) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showPickerView();
                    }
                });
            } else {
                Toast.makeText(mContext, "获取地区信息失败，请稍后重试", Toast.LENGTH_SHORT).show();
            }
        }

        @JavascriptInterface
        public void close() {
            finish();
        }

        @JavascriptInterface
        public void setEditorState(boolean b) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (!b) {
                        setTopRightButton("管理", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                activityAddressWebBinding.webView.loadUrl("javascript:edit(true)");
                            }
                        });
                    } else {
                        setTopRightButton("完成", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                activityAddressWebBinding.webView.loadUrl("javascript:edit(false)");
                            }
                        });
                    }
                }
            });
        }
    }
}

